import os
os.environ['KMP_DUPLICATE_LIB_OK'] = 'TRUE'  # 设置环境变量

import cv2
import easyocr

# 读取验证码图片
captcha_img = cv2.imread("captcha.png", cv2.IMREAD_GRAYSCALE)

# 高级图像预处理
# 自适应二值化
adaptive_img = cv2.adaptiveThreshold(captcha_img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 11, 2)

# 边缘检测（可选）
edges = cv2.Canny(adaptive_img, 50, 150)

# 噪声去除
cleaned_img = cv2.medianBlur(edges, 3)

# 使用EasyOCR进行识别
reader = easyocr.Reader(['en'], gpu=False)  # 初始化EasyOCR
captcha_text = reader.readtext(cleaned_img, detail=0, paragraph=True).strip()

print("✅ 验证码识别完成:", captcha_text)

# 如果需要进一步解析表达式并计算结果
if 'x' in captcha_text:
    expression = captcha_text.replace('x', '*')  # 将 'x' 替换为 '*' 以便计算
    try:
        result = eval(expression.split('=')[0])  # 计算表达式结果
        print("计算结果为：", result)
    except Exception as e:
        print("表达式计算错误：", e)
